<template>
  <div class="common-layout" style="height: 600px;">
      <el-header style="border-style: groove;border-width: 2px;height: 100px;">
        <el-form-item label="商品名称" style="margin-top: 25px;">
          <el-select v-model="state.foodId" placeholder="请选择" style="width: 200px;">
            <el-option v-for="item in foodList2" :label="item.foodName" :value="item.foodId" />
          </el-select>&nbsp;&nbsp;&nbsp;&nbsp;
          <el-button type="primary" @click="getProduct()">搜索</el-button>
        </el-form-item> 
        
      </el-header>
      <el-main style="border-style: groove;border-width: 2px;height: 450px;margin-top: 20px;">
        <el-button type="primary" @click="open(null)">新增</el-button>
        <el-button type="danger" @click="delProduct()">删除</el-button>
        <el-table :data="productList" border style="width: 100%;" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="productCode" label="商品编号" width="80" />
          <el-table-column prop="foodName" label="商品名称" width="100" />
          <el-table-column prop="productionBatch" label="生产批次" width="100" />
          <el-table-column prop="shelfLife" label="保质期" width="80" />
          <el-table-column prop="licenseNumber" label="生产许可证" width="130" />
          <el-table-column prop="enterprise" label="生产企业" width="130" />
          <el-table-column prop="creator" label="创建人" width="80" />
          <el-table-column prop="createTime" label="创建时间" width="150" >
            <template #default="{row}">
              {{ row.createTime.substring(0,16) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="{row}">
                 <el-button type="warning" size="small" @click="open(row)">编辑</el-button>
                 <el-button type="success" size="small" @click="fanProject(row)">查看详情</el-button>
            </template>
            
          </el-table-column>
        </el-table>
        <!--分页-->
          <table>
            <tr>
              <td>
                <el-pagination
      v-model:current-page="state.PageIndex"
      v-model:page-size="state.PageSize"
      :page-sizes="[3, 5, 8, 10]"
      :background="true"
      prev-text="上一页"
      next-text="下一页"
      layout="total,slot, sizes"
      :total="totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >当前：<span>{{ state.PageIndex }}</span>/<span>{{ totalPage }}</span>页</el-pagination>
              </td>
              <td>
                <el-pagination
      v-model:current-page="state.PageIndex"
      v-model:page-size="state.PageSize"
      :page-sizes="[3, 5, 8, 10]"
      :background="true"
      prev-text="上一页"
      next-text="下一页"
      layout="slot, prev, pager"
      :total="totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ><el-button type="primary" @click="handleCurrentChange(1)">首页</el-button></el-pagination>
              </td>
              <td>
                <el-pagination
      v-model:current-page="state.PageIndex"
      v-model:page-size="state.PageSize"
      :page-sizes="[3, 5, 8, 10]"
      :background="true"
      prev-text="上一页"
      next-text="下一页"
      layout="next,slot, jumper"
      :total="totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ><el-button type="primary" @click="handleCurrentChange(totalPage)">尾页</el-button></el-pagination>
              </td>
            </tr>
          </table>
        <!--分页-->
      </el-main>
  </div>
  <el-dialog v-model="isLock.isOpen" :title="isLock.title" width="500">
    <el-form :model="form" :rules="rules" ref="ruleFormRef" style="max-width: 600px" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="商品名称">
          <el-select v-model="form.foodId" placeholder="请选择">
            <el-option v-for="item in foodList" :label="item.foodName" :value="item.foodId" />
          </el-select>
        </el-form-item>
        <el-form-item label="生产批次" prop="productionBatch">
          <el-input v-model="form.productionBatch" :disabled="true" />
        </el-form-item>
        <el-form-item label="保质期（天）" prop="shelfLife">
          <el-input v-model="form.shelfLife" />
        </el-form-item>
        <el-form-item  label="生产许可证号" prop="licenseNumber">
          <el-input v-model="form.licenseNumber"/>
        </el-form-item>
        <el-form-item label="生产企业" prop="enterprise">
          <el-input v-model="form.enterprise" />
        </el-form-item>
        <el-form-item label="图片" prop="photoUrl">
          <el-upload
        class="avatar-uploader"
        action="https://localhost:44391/api/Management/UploadFile"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
    <img v-if="form.photoUrl" :src="'https://localhost:44391/img/'+form.photoUrl" class="avatar" style="max-width: 100px;max-height: 100px;" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
        </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button >取消</el-button>
        <el-button type="primary" @click="save()">保存</el-button>
      </div>
    </template>
  </el-dialog> 
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue'
import { ElMessage, ElMessageBox, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios';
import { useRouter } from 'vue-router';
import {useCounterStore} from '@/stores/counter'
import { Plus } from '@element-plus/icons-vue'
import moment from 'moment';
import type { UploadProps } from 'element-plus'
const formSize = ref<ComponentSize>('default')
const imageUrl = ref('')
const store = useCounterStore()
const router = useRouter()
interface RuleForm {
}
const rules = reactive<FormRules<RuleForm>>({
})
//验证
// const rules = reactive<FormRules<RuleForm>>({
//   foodId: [
//     {required: true,message: '请选择商品',trigger: 'change'},
//   ],
//   shelfLife:[
//     {required: true, message: '请输入保质期', trigger: 'blur'},
//     {pattern:/^[0-9]\d/,message: '请输入数字', trigger: 'blur'},
//     {  max: 5, message: '不能超过5位数', trigger: 'blur' },
//   ],
//   licenseNumber: [
//     { required: true, message: '生产许可证不能为空', trigger: 'blur' },
//     { max: 20, message: '最大不能超过20位字符', trigger: 'blur' },
//   ],
//   enterprise:[
//   { required: true, message: '生产企业不能为空', trigger: 'blur' },
//   { max: 20, message: '最大不能超过20位字符', trigger: 'blur' },
//   ],
//   photoUrl: [
//     { required: true, message: '图片必须上传', trigger: 'blur' },
//   ],
// })
const handleAvatarSuccess =(picName:string)=> {
  form.photoUrl=picName;
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
 if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('大小不能超过2MB!')
    return false
  }
  return true
}
const data:any=reactive({
  state:{
    PageIndex:1,
    PageSize:3,
    foodId:'',
    productId:''
  },
  totalCount:0,
  totalPage:0
})
const {state,totalCount,totalPage} = toRefs(data)
//   isLock.isOpen=true
//   urform.userId=row.userId
//   console.log(row)
//   //反填多选框
//   getUserRole()
// }
// const save=()=>{
//   let obj={
//     userId:urform.userId,
//     roleId:urform.roleId.toString()
//   }
//   axios({
//     url:'https://localhost:7011/api/Management/UserRoleAdd',
//     method:'post',
//     data:obj
//   })
//   .then(res=>{
//     if(res.data.code==300){
//       ElMessage.success(res.data.msg)
//       urform.roleId=[]
//     }else{
//       ElMessage.error(res.data.msg)
//     }
//     isLock.isOpen=false
//     console.log(res)
//   })
//   .catch(err=>{
//     console.log(err)
//   })
// }

//获取字典类型列表
const productList:any=ref([])
const getProduct = ()=>{
  let obj={
    PageIndex:state.value.PageIndex,
    PageSize:state.value.PageSize,
    foodId:state.value.foodId||0
  }
  axios({
    url:'https://localhost:44391/api/Management/GetProduct',
    method:'get',
    params:obj
  })
  .then(res=>{
    productList.value=res.data.data.pageList
    totalCount.value=res.data.data.totalCount
    totalPage.value=res.data.data.totalPage
    console.log(res)
  })
  .catch(err=>{
    console.log(err)
  })
}
const handleSizeChange = (val: number) => {
  state.value.PageSize=val
  getProduct()
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  state.value.PageIndex=val
  getProduct()
  console.log(`current page: ${val}`)
}
// //停用人员
// const delDictItem=(row:any)=>{
//   ElMessageBox.confirm(
//     '确认要停用此权限吗?',
//     '警告',
//     {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'warning',
//     }
//   )
//     .then(() => {
//       let obj={
//         dictItemId:row.dictItemId
//   }
//   axios({
//     url:'https://localhost:7011/api/Management/DictItemDel',
//     method:'post',
//     data:obj
//   })
//   .then(res=>{
//     if(res.data.code==400){
//       ElMessage.success(res.data.msg)
//       getDictItem()
//     }else{
//       ElMessage.error(res.data.msg)
//     }
//     console.log(res)
//   })
//   .catch(err=>{
//     console.log(err)
//   })
//     })
//     .catch(() => {
//       ElMessage({
//         type: 'info',
//         message: 'Delete canceled',
//       })
//     })
  
// }
// //编辑人员
const isLock=reactive({
  isOpen:false,
  title:'',
  isAdd:false
})
const form:any=reactive({
  productId:'',
  productCode:'',
  foodId:'',
  productionBatch:'',
  shelfLife:'',
  licenseNumber:'',
  enterprise:'',
  creator:store.counterAccount.accountNicName,
  createTime:Date.now,
  updator:store.counterAccount.accountNicName,
  updateTime:Date.now,
  deletor:store.counterAccount.accountNicName,
  deleteTime:Date.now,
  photoUrl:''
})
const open=(row:any)=>{
  isLock.isOpen=true
  if(row==null){
    isLock.isAdd=true
    isLock.title="新增"
    form.productCode=''
    form.foodId=''
    form.productionBatch=dateList
    // form.productionBatch=moment().format("YYYYMMDDHHmmssSSS")
    form.shelfLife=''
    form.licenseNumber=''
    form.enterprise=''
    form.photoUrl=''
  }else{
    isLock.isAdd=false
    isLock.title="编辑"
    form.productId=row.productId
    form.productCode=row.productCode
    form.foodId=row.foodId
    form.productionBatch=row.productionBatch
    form.shelfLife=row.shelfLife
    form.licenseNumber=row.licenseNumber
    form.enterprise=row.enterprise
    form.photoUrl=row.photoUrl
  }
}
const save=()=>{
  if(isLock.isAdd){
    if(form.foodId==''){
      ElMessage.error("请选择商品名称")
      return
    }
    if(form.shelfLife==''){
      ElMessage.error("保质期为空")
      return
    }
    if(form.licenseNumber==''){
      ElMessage.error("生产许可证号为空")
      return
    }
    if(form.enterprise==''){
      ElMessage.error("生产企业为空")
      return
    }
    if(form.photoUrl==''){
      ElMessage.error("图片为空")
      return
    }
    axios({
    url:'https://localhost:7223/api/Management/ProductAdd',
    method:'post',
    data:form
  })
  .then(res=>{
    if(res.data.code==300){
      ElMessage.success(res.data.msg)
      getProduct()
      // router.push('/rolelist')
    }else{
      ElMessage.error(res.data.msg)
    }
    console.log(res)
    isLock.isOpen=false
  })
  }else{
    axios({
    url:'https://localhost:7223/api/Management/ProductUpd',
    method:'post',
    data:form
  })
  .then(res=>{
    if(res.data.code==500){
      ElMessage.success(res.data.msg)
      getProduct()
      // router.push('/rolelist')
    }else{
      ElMessage.error(res.data.msg)
    }
    console.log(res)
    isLock.isOpen=false
  })
  }
  
}
//逻辑删除
const multipleSelection:any=ref([])
const handleSelectionChange = (val:any) => {
  multipleSelection.value = val
}
const delProduct=()=>{
  ElMessageBox.confirm(
    '确认要删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      if(multipleSelection.value.length==0)
  {
    ElMessage.error("至少选择一个")
   return;
  }
  else
  {
      let  idss=multipleSelection.value.map((x:any)=>x.productId)
                  var  productId="";
              productId=idss.toString();
                    console.log(productId)
              let obj = {
                productId:productId
              }
       axios.post('https://localhost:7223/api/Management/ProductDel',obj).then(res=>
       {
         if(res.data.code==400)
         {
          ElMessage.success(res.data.message)
          getProduct()
         }
         else
         {
          ElMessage.error(res.data.message)
         }
       })
      
  }
    })
    .catch(() => {
      ElMessage({
        type:'warning',
        message: '取消删除',
      })
    })
  
}
//食物下拉
const foodList:any=ref([])
const GetFood = ()=>{
  axios({
    url:'https://localhost:44391/api/Management/GetFood',
    method:'get'
  })
  .then(res=>{
    foodList.value=res.data.data
    console.log(res)
  })
  .catch(err=>{
    console.log(err)
  })
}
const foodList2:any=ref([])
const GetFood2= ()=>{
  axios({
    url:'https://localhost:44391/api/Management/GetFood',
    method:'get'
  })
  .then(res=>{
    foodList2.value=res.data.data
    console.log(res)
  })
  .catch(err=>{
    console.log(err)
  })
}
//获取当前时间
const dateList:any=ref([])
const GetDate= ()=>{
  axios({
    url:'https://localhost:44391/api/Management/GetDate',
    method:'get'
  })
  .then(res=>{
    dateList.value=res.data
    console.log(res)
  })
  .catch(err=>{
    console.log(err)
  })
}
//反填信息
const fanProject=(row:any)=>{
  router.push({
    name:'details',
    query:{
      productId:row.productId
    }
  })
}
onMounted(()=>{
  getProduct()
  GetFood()
  GetDate()
  GetFood2()
})
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>